package com.cskaoyan.service.impl;

import com.cskaoyan.bean.Address;
import com.cskaoyan.bean.AddressExample;
import com.cskaoyan.bean.BasePageData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.mapper.AddressMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.service.AddressService;
import com.cskaoyan.utils.CommonUtil;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.MarketPageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public BasePageData addressQueryByName(Integer id) {
        //找用户表对应的用户id
        BaseParam param = new BaseParam();
        param.setSort(Constant.SORT);
        param.setOrder(Constant.ORDER);
        //条件配置
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(id);

        //设置排序
        addressExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        //查询
        List<Address> addressList = addressMapper.selectByExample(addressExample);
        Integer l = addressMapper.countByExample(addressExample);
        param.setLimit(l);
        param.setPage(Constant.WX_PAGE);
        //分页配置
        MarketPageUtil.startPage(param);
        //分页结果接收 内置在BasePageData中
        return BasePageData.ok(addressList);

    }

    @Override
    public Address addressQueryById(Integer id) {

        Address address = addressMapper.selectByPrimaryKey(id);

        return address;

    }

    @Override
    public int createAddress(Address address) {
        address.setUserId(CommonUtil.getUserId());
        if (address.getIsDefault() == true) {
            Integer integer = addressMapper.selectByUserId(address.getUserId());
            //integer有可能是null，不用另外更新
            if (integer != null) addressMapper.updateNotDefault(integer);
        }
        return addressMapper.insertSelective(address);

    }

    @Override
    public int updateAddress(Address address) {
        address.setUserId(CommonUtil.getUserId());
        if (address.getIsDefault() == true) {
            Integer integer = addressMapper.selectByUserId(address.getUserId());
            //integer有可能是null，不用另外更新
            if (integer != null) addressMapper.updateNotDefault(integer);
        }
        return addressMapper.updateByPrimaryKey(address);
    }

    @Override
    public int deleteAddress(Integer id) {
        return addressMapper.deleteByPrimaryKey(id);
    }
}
